<template>
	<z-paging ref="paging" v-model="dataList" @query="queryList" :empty-view-center="false" :loading-more-enabled="false" :refresher-enabled="false" :auto="false">
		<view class="container">
			<view class="example">
				<!-- 基本信息 -->
				<view class="classifyItem header">
					<view class="classifyItemHead">
						<text>基本信息</text>
					</view>
				</view>
				<view class="classifyItem">
					<view class="baseFormItem">
						<text class="title">商品名称</text>
						<uni-easyinput type="text" v-model="shopForm.commodity" placeholder="请填写" disabled></uni-easyinput>
					</view>
					<view class="baseFormItem">
						<text class="title">
							<text class="required">*</text>
							装车日期
						</text>
						<uni-datetime-picker type="date" v-model="shopForm.loadingTime" />
					</view>

					<view class="baseFormItem">
						<text class="title">装车地点</text>
						<uni-easyinput type="text" v-model="shopForm.loadingAddress" placeholder="请输入" disabled></uni-easyinput>
					</view>

					<view class="baseFormItem">
						<text class="title">卸车地点</text>
						<uni-easyinput type="text" v-model="shopForm.unloadAddress" placeholder="请输入" disabled></uni-easyinput>
					</view>

					<view class="baseFormItem">
						<text class="title">运费单价</text>
						<uni-easyinput type="digit" v-model="shopForm.freightPrice" placeholder="请输入" disabled></uni-easyinput>
					</view>
				</view>
				<!-- 车辆列表 -->
				<uni-forms>
					<uni-collapse v-model="collapse">
						<uni-collapse-item :name="`collapse${index}`" v-for="(item, index) in Forms.data" :key="index">
							<template v-slot:title>
								<view class="classifyItem">
									<view class="classifyItemHead">
										<text>车辆{{ index + 1 }}</text>
										<view class="carUserData">
											<text>{{ Forms.data[index].vehicleNo ? `车号${Forms.data[index].vehicleNo}` : '' }}</text>
											<text>{{ Forms.data[index].driverName ? `司机${Forms.data[index].driverName}` : '' }}</text>
										</view>
										<view class="carUserBtn">
											<image v-if="index !== 0" @click.stop="removeItem(index)" class="deleteIcon" src="/static/delete.png" mode="widthFix"></image>
											<u-button v-if="index == Forms.data.length - 1" type="primary" size="mini" @click.stop="addSpecies">新增车辆</u-button>
										</view>
									</view>
								</view>
							</template>
							<!-- 自动识别弹窗 -->
							<!-- <automatic-identification-vue @ok="(data) => fillReport(data, index)"></automatic-identification-vue> -->
							<view class="classifyItem">
								<view class="baseFormItem">
									<text class="title">
										<text class="required">*</text>
										车号
									</text>
									<uni-easyinput
										type="text"
										v-model="Forms.data[index].vehicleNo"
										placeholder="请输入"
										maxlength="7"
										@input="($event) => getDriver($event, index)"
									></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">挂车号</text>
									<uni-easyinput type="text" v-model="Forms.data[index].trailerNo" placeholder="请输入" maxlength="7"></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">
										<text class="required">*</text>
										司机姓名
									</text>
									<uni-easyinput type="text" v-model="Forms.data[index].driverName" placeholder="请输入"></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">身份证号</text>
									<uni-easyinput type="idcard" maxlength="18" v-model="Forms.data[index].driverIdcard" placeholder="请输入"></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">手机号</text>
									<uni-easyinput type="number" maxlength="11" v-model="Forms.data[index].driverPhone" placeholder="请输入"></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">押运员姓名</text>
									<uni-easyinput type="text" v-model="Forms.data[index].pledgeName" placeholder="请输入"></uni-easyinput>
								</view>

								<view class="baseFormItem">
									<text class="title">押运员身份证号</text>
									<uni-easyinput type="idcard" maxlength="18" v-model="Forms.data[index].pledgeIdcard" placeholder="请输入"></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">押运员手机号</text>
									<uni-easyinput type="number" maxlength="11" v-model="Forms.data[index].pledgePhone" placeholder="请输入"></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">
										<text class="required">*</text>
										预装吨位
									</text>
									<uni-easyinput type="digit" v-model="Forms.data[index].tonnage" placeholder="请输入"></uni-easyinput>
								</view>
								<view class="baseFormItem">
									<text class="title">运输公司名称</text>
									<uni-easyinput v-model="Forms.data[index].companyName" placeholder="请输入"></uni-easyinput>
								</view>
								<!-- {{ header }} -->
								<view class="baseFormItem">
									<text class="title">驾驶证</text>
									<u-upload
										:key="affixForMat[index].driverAffix.length"
										width="110"
										height="110"
										ref="rupload"
										:max-count="1"
										:max-size="15 * 1024 * 1024"
										upload-text="上传"
										@on-choose-complete="onChooseComplete"
										@on-success="(data) => onSuccess(data, index, 'jsz')"
										@on-remove="(idx) => onRemove(idx, index, 'jsz')"
										@on-oversize="() => overSize('驾驶证')"
										@on-error="onError"
										:header="header"
										:file-list="affixForMat[index].driverAffix"
										:action="baseFilesURL"
									></u-upload>
									<!-- <text class="maxLength">最多上传9张图片</text> -->
								</view>
								<view class="baseFormItem">
									<text class="title">行驶证</text>
									<u-upload
										:key="affixForMat[index].travelAffix.length"
										width="110"
										height="110"
										ref="rupload"
										:max-count="1"
										:max-size="15 * 1024 * 1024"
										upload-text="上传"
										@on-choose-complete="onChooseComplete"
										@on-success="(data) => onSuccess(data, index, 'xsz')"
										@on-remove="(idx) => onRemove(idx, index, 'xsz')"
										@on-oversize="() => overSize('行驶证')"
										@on-error="onError"
										:header="header"
										:file-list="affixForMat[index].travelAffix"
										:action="baseFilesURL"
									></u-upload>
									<!-- <text class="maxLength">最多上传9张图片</text> -->
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</uni-forms>
			</view>
		</view>

		<template v-slot:bottom>
			<view class="btnBox">
				<view class="btnBoxOut btnBoxSubmit" @click="formAction">
					<text class="btnBoxOutText">提交</text>
				</view>
				<!-- <view class="btnBoxOut btnBoxOutAdd" @click="addSpecies">
					<text class="btnBoxOutText">+</text>
				</view> -->
			</view>
		</template>
	</z-paging>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeMount, computed, toRef, toRefs, watch } from 'vue';
import http from '@/common/request.js';
import { baseFilesURL, baseFilesVisitURL } from '@/common/request.js';
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import { getDriverToNo, getReportCarList, saveCar } from '../../../../../api/logisitcsCompany';
import { getToken } from '../../../../../common/user';
import { navBack, setLoadingToast, setToast } from '../../../../../common/utils';
import { cloneDeep } from 'lodash';
import automaticIdentificationVue from '../../../../../components/automaticIdentification.vue';

const header = {
	'Cache-Id': getToken()
};

const dataList = ref([{}]);
const paging = ref(null);
// 基本信息
const shopForm = reactive({
	id: null,
	commodity: '',
	loadingTime: '',
	loadingAddress: '',
	unloadAddress: '',
	freightPrice: ''
});
// 折叠
const collapse = ref(['collapse0']);

// order/detail/ids/1
const emmptyObject = {
	vehicleNo: '', //车号
	trailerNo: '', //挂车号
	driverName: '', //司机姓名
	driverIdcard: '', //身份证号
	driverPhone: '', // 手机号
	pledgeName: '', //押运员姓名
	pledgeIdcard: '', //押运员身份证号
	pledgePhone: '', //押运员手机号
	tonnage: '', //装车吨位
	companyName: '', //运输公司名称
	driverAffix: [], //驾驶证
	travelAffix: [] //行驶证
};

const Forms = reactive({
	data: []
});

// 添加司机
const addSpecies = () => {
	const deep = cloneDeep(emmptyObject);
	Forms.data.push(deep);
};

// 司机驾驶证,行驶证 处理
const affixForMat = computed(() => {
	const deeps = cloneDeep(Forms.data);
	return deeps.map((v) => {
		// 驾驶证
		v.driverAffix = v.driverAffix.map((v) => {
			v.url = baseFilesVisitURL + v.path;
			return v;
		});
		// 行驶证
		v.travelAffix = v.travelAffix.map((v) => {
			v.url = baseFilesVisitURL + v.path;
			return v;
		});

		return v;
	});
});

// ai 识别后
const fillReport = (data, index) => {
	// 填充
	// Forms.data[index] = data
};

// 操作表单
const formAction = () => {
	if (!shopForm.loadingTime) {
		return setToast('请选择装车日期');
	}

	if (validateData()) {
		console.log('所有字段已填写');
		setLoadingToast('录入中...');
		Forms.data = Forms.data.map((v) => {
			v.driverAffix = JSON.stringify(v.driverAffix);
			v.travelAffix = JSON.stringify(v.travelAffix);
			return v;
		});
		// 保存
		saveCar({
			needId: shopForm.id,
			needInfos: Forms.data,
			loadingTime: shopForm.loadingTime
		}).then((res) => {
			uni.hideLoading();
			if (res.code == 1) {
				setToast('录入成功');
				uni.$emit('updatestaff');
				setTimeout(() => {
					navBack();
				});
			}
		});
	} else {
		console.log('有字段没写');
	}
};

// 验证函数，检查数组中的每个对象的每个字段是否都被填写
const keys = {
	vehicleNo: '车号',
	// trailerNo: '挂车号',
	driverName: '司机姓名',
	// driverIdcard: '身份证号',
	// driverPhone: '手机号',
	// pledgeName: '押运员姓名',
	// pledgeIdcard: '押运员身份证号',
	// pledgePhone: '押运员手机号',
	tonnage: '预装吨位'
	// companyName: '运输公司名称',
	// driverAffix: '驾驶证',
	// travelAffix: '行驶证'
};

const validateData = () => {
	const data = Forms.data;
	for (var i = 0; i < data.length; i++) {
		var item = data[i];
		for (var key in item) {
			if (item.hasOwnProperty(key) && item[key] === '' && keys[key]) {
				setToast(`车辆${i + 1}中${keys[key]}未填写`);
				return false;
			}
			const coard = ['driverIdcard'];
			const phone = ['driverPhone'];
			// 如果 key 是 coard 中的，使用正则验证是否是身份证号
			if (coard.includes(key) && keys[key] && !/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/.test(item[key])) {
				setToast(`车辆${i + 1}中${keys[key]}不是有效的身份证号`);
				return false;
			}

			// 如果 key 是 phone 中的，使用正则验证是否是手机号
			if (phone.includes(key) && keys[key]) {
				if (!/^1[3456789]\d{9}$/.test(item[key])) {
					setToast(`车辆${i + 1}中${keys[key]}不是有效的手机号`);
					return false;
				}
			}
		}
	}
	// 循环结束后返回 true，表示所有字段都已填写
	return true;
};

const removeItem = (i) => {
	uni.showModal({
		title: '提示',
		content: '确认删除此项吗?请谨慎操作!',
		showCancel: true,
		cancelText: '取消',
		confirmText: '删除',
		success: (res) => {
			if (res.confirm) {
				Forms.data.splice(i, 1);
			}
		},
		fail: () => {},
		complete: () => {}
	});
};

const onError = (res, index, type) => {
	setToast('图片上传失败');
};

const onChooseComplete = () => {
	setLoadingToast('上传中...');
};

const onSuccess = (data, arrIndex, type) => {
	// type == jsz  驾驶证
	// type == xsz  行驶证
	// 图片添加类型（PC展示需要此类型）
	// data.data.type = 'image';
	// Forms.data[arrIndex][type == 'jsz' ? 'driverAffix' : 'travelAffix'].push(data.data);
	// setToast('上传成功');

	// type == jsz  驾驶证
	// type == xsz  行驶证
	// 图片添加类型（PC展示需要此类型）
	uni.hideLoading();
	// type == loading  装车
	// type == unload  卸车
	// loadingPoundAffix unloadPoundAffix
	const dep = data.data;
	// 图片添加类型（PC展示需要此类型）
	dep.type = 'image';
	dep.suffix = '.' + dep.suffix;
	if (type == 'jsz') {
		Forms.data[arrIndex].driverAffix.push(dep);
	} else {
		Forms.data[arrIndex].travelAffix.push(dep);
	}
	setToast('上传成功');
};

// 移除文件 删除 Forms.value.image
const onRemove = (index, arrIndex, type) => {
	// type == jsz  驾驶证
	// type == xsz  行驶证
	Forms.data[arrIndex][type == 'jsz' ? 'driverAffix' : 'travelAffix'].splice(index, 1);
	setToast('删除成功');
};

// 查询填报的司机信息
const imgsKeys = ['driverAffix', 'travelAffix'];
const getData = (id) => {
	setLoadingToast('获取车辆中');
	getReportCarList(id).then((res) => {
		uni.hideLoading();
		if (res.code) {
			const deeps = res.data.rows.map((v) => {
				return fillIn(v);
			});
			// 回显
			if (deeps.length) {
				Forms.data = deeps;
			}
		}
	});
};

// 处理每一项数据格式化，图片信息等
const fillIn = (v) => {
	const item = {};
	for (let keys in emmptyObject) {
		if (imgsKeys.includes(keys)) {
			// 图片回显
			const dep = v[keys] ? JSON.parse(v[keys]) : [];
			if (dep.length) {
				dep[0].url = baseFilesVisitURL + dep[0].path;
			}
			item[keys] = dep;
		} else {
			// 如果是undefined或者null 赋值为字符串
			console.log('v ===>  ', v);
			item[keys] = v[keys] || '';
		}
	}
	return item;
};

// 查询
const getDriver = (vehicleNo, index) => {
	// 车号不完整 不匹配查找, 如果已经有司机姓名 不查找
	if (vehicleNo.length < 7 || Forms.data[index].driverName) {
		return;
	}

	const vdx = Forms.data.filter((v, ti) => ti !== index && v.vehicleNo === vehicleNo);
	// 验证重复逻辑
	if (vdx.length) {
		setToast('车号重复');
		return;
	}
	// 车号不重复，查询是否有信息数据
	getDriverToNo(vehicleNo).then((res) => {
		const v = res.data;
		// 判断是否已经填写
		if (res.code && v) {
			uni.showModal({
				title: '提示',
				content: `查询到车辆${vehicleNo}的信息，是否填充到表单？`,
				showCancel: true,
				cancelText: '关闭',
				confirmText: '填充',
				success: (res) => {
					if (res.confirm) {
						const item = fillIn(v);
						Forms.data.splice(index, 1, item);
						setToast('请确认车辆信息无误');
					}
				},
				fail: () => {},
				complete: () => {}
			});
		}
	});
};
// 图片大小超出限制
const overSize = (name) => {
	setToast(`${name}大小超出限制15MB`);
};

onLoad((options) => {
	const D = JSON.parse(decodeURIComponent(options.item));
	if (D.data) {
		// 参数回显
		Object.keys(D.data).forEach((key) => {
			// shopForm
			if (shopForm.hasOwnProperty(key)) {
				if (key == 'freightPrice') {
					// shopForm.freightPrice
					shopForm[key] = D.data[key] ? D.data[key] / 1000 : 0;
				} else {
					shopForm[key] = D.data[key];
				}
			}
		});
	}

	const deep = cloneDeep(emmptyObject);
	Forms.data.push(deep);
	// getData(D.data.id);
});
</script>

<style scoped lang="scss">
.addCarBtn {
	// border: 1px solid red;
}

.btnBox {
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 50rpx;
	overflow: hidden;
	padding: 40rpx;

	.btnBoxOut {
		margin-left: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #2c7be7;
		height: 90rpx;
		line-height: 90rpx;
		border-radius: 50rpx;

		.btnBoxOutText {
			color: #fff;
		}
	}
	.btnBoxSubmit {
		flex: 1;
	}
	.btnBoxOutAdd {
		background-color: #93bbf3;
		width: 90rpx;
	}
}

.container {
	padding: 30rpx;
	box-sizing: border-box;

	.example {
		.baseFormItem {
			// border: 1rpx solid red;
			background-color: #fff;
			padding: 20rpx;
			border-radius: 10rpx;
			margin-top: 20rpx;

			.maxLength {
				font-size: 28rpx;
				margin-left: 10rpx;
			}

			.gjBox {
				display: flex;
				justify-content: space-between;

				.item {
					margin: 15rpx 5rpx;
					width: 120rpx;
					height: 120rpx;
					background-color: #dddddd;
					border-radius: 10rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					text-align: center;
					padding: 5rpx;
					box-sizing: border-box;
				}

				.selcet {
					background-color: #65d488;
					color: #fff;
				}
			}
		}

		.filesUpload {
			width: 670rpx;
			height: 424rpx;
			margin: 0 0 40rpx 0;
			position: relative;
			box-sizing: border-box;

			.clickBox {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				border-radius: 20rpx;
				background: #dcdcdc;
				z-index: 99;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 20rpx;
				box-sizing: border-box;
				overflow: hidden;

				.clickBoxAddImage_yicun {
					width: 100%;
					height: 100%;
				}

				.clickBoxItem {
					display: flex;
					justify-content: center;
					align-items: center;
				}

				.clickBoxAddImage {
					width: 50rpx;
					height: 50rpx;
				}

				.clickText {
					font-size: 30rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #999999;
				}
			}
		}
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
}

.interestedStudents_end {
	padding: 40rpx;

	.button_end {
		margin: 25rpx 0 !important;
	}
}

.uni-forms-item__inner {
	padding-bottom: 10rpx;
}

.classifyItem {
	.baseFormItem {
		margin-top: 0 !important;
		border-radius: 0 !important;
		// border: 1rpx solid red;
		display: flex;
		align-items: center;

		.title {
			width: 120rpx;
			overflow: hidden;
			font-size: 26rpx;
			// text-align: ce;
		}
	}

	.classifyItemHead {
		font-size: 26rpx;
		color: #999999;
		padding: 20rpx 0;
		display: flex;
		justify-content: space-between;

		.deleteIcon {
			width: 30rpx;
			height: 30rpx;
			margin-right: 20rpx;
		}

		.carUserData {
			// border: 1rpx solid red;
			flex: 1;
			font-weight: 500;
			margin-left: 50rpx;
			font-size: 25rpx;

			text {
				margin-right: 20rpx;
			}
		}

		.carUserBtn {
			display: flex;
			// border: 1px solid red;
			align-items: center;
		}
	}
}

.header {
	.classifyItemHead {
		color: #51a9ec;
		font-size: 26rpx;
	}
}
</style>
